package com.vise.bledemo.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;

import com.vise.bledemo.R;
import com.vise.bledemo.fragment.BraceletFragment;
import com.vise.bledemo.fragment.HomeFragment;
import com.vise.bledemo.fragment.MineFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * TabLayout+ViewPager滑动点击切换
 * 进入会初始化当前的Fragment和下一个Fragment,然后往后滑动一个执行下一个,只执行一次,往回滑不执行
 */

public class MainActivity4 extends AppCompatActivity {


    ViewPager mContentVp;
    TabLayout mTabs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        mContentVp = (ViewPager) findViewById(R.id.content_vp);
        mTabs = (TabLayout) findViewById(R.id.tabs);
        initFragment();
    }

    private void initFragment() {

        List<String> titles = new ArrayList<>();
        titles.add("首页");
        titles.add("手环");
        titles.add("我的");


        for (int i = 0; i < titles.size(); i++) {
            mTabs.addTab(mTabs.newTab().setText(titles.get(i)));
        }

        ArrayList<Fragment> datas = new ArrayList<>();
        datas.add(new HomeFragment());
        datas.add(new BraceletFragment());
        datas.add(new MineFragment());


        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), datas, titles);
        mContentVp.setAdapter(fragmentAdapter);
        mContentVp.setCurrentItem(0);
        //将TabLayout和ViewPager关联起来。
        mTabs.setupWithViewPager(mContentVp);
        //给TabLayout设置适配器
        mTabs.setTabsFromPagerAdapter(fragmentAdapter);
    }

    class FragmentAdapter extends FragmentPagerAdapter {

        private final List<String> mTitles;
        private List<Fragment> info;

        public FragmentAdapter(FragmentManager fm, List<Fragment> info, List<String> titles) {
            super(fm);
            this.info = info;
            mTitles = titles;

        }


        @Override
        public Fragment getItem(int position) {
            return info.get(position);
        }

        @Override
        public int getCount() {
            return info.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;

        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (null == mTitles)
                return null;
            else
                return mTitles.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

        }
    }
}